package com.lagou.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Activate(group = {CommonConstants.PROVIDER})
public class TPMonitorFilter implements Filter {

    public static ConcurrentHashMap<String, List<MethodRespone>> map = new ConcurrentHashMap<>();

    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long   startTime  = System.currentTimeMillis();
        String methodName = invocation.getMethodName();
        try {
            // 执行方法
            return  invoker.invoke(invocation);
        } finally {
            long duration = System.currentTimeMillis() - startTime;
            MethodRespone methodRespone = new MethodRespone(LocalDateTime.now(), duration);
            if("methodA".equals(methodName)){
                List<MethodRespone> listA = map.get("methodA");
                if(listA == null || listA.size()== 0){
                    listA = new ArrayList<>();
                }
                listA.add(methodRespone);
                map.put("methodA",listA);
            }else if("methodB".equals(methodName)){
                List<MethodRespone> listB = map.get("methodB");
                if(listB == null || listB.size()== 0){
                    listB = new ArrayList<>();
                }
                listB.add(methodRespone);
                map.put("methodB",listB);
            }else {
                List<MethodRespone> listC = map.get("methodC");
                if(listC == null || listC.size()== 0){
                    listC = new ArrayList<>();
                }
                listC.add(methodRespone);
                map.put("methodC",listC);
            }

        }

    }
}
